package cn.wanho.handler;

import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import java.io.IOException;

/**
 * 拦截请求url
 * 权限拦截器
 */
@Component
public class UserAbstractSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
    @Resource
    UserFilterInvocationSecurityMetadatasource userFilterInvocationSecurityMetadatasource;

    /**
     * 绑定决策管理器
     * @param userAccessDecisionManager
     */
    @Resource
    public void setMyAccessDecisionManager(UserAccessDecisionManager userAccessDecisionManager){
        super.setAccessDecisionManager(userAccessDecisionManager);
    }
    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return this.userFilterInvocationSecurityMetadatasource;
    }

    public void invoke(FilterInvocation fi) throws ServletException, IOException {
        InterceptorStatusToken token = super.beforeInvocation(fi);
        try {
            fi.getChain().doFilter(fi.getRequest(),fi.getResponse());
        }  finally {
            super.afterInvocation(token,null);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        FilterInvocation filterInvocation = new FilterInvocation(servletRequest, servletResponse, filterChain);
        invoke(filterInvocation);
    }
}
